<template>
  <div>
    搜索建议
    <van-cell v-for="(item, i) in list" :key="i" icon="search">
      <div @click="$emit('search-keys', item)" slot="title" v-html="lightStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { steerData } from '@/api/search'
import { debounce } from 'lodash'
console.dir(debounce)
export default {
  props: {
    serachKeys: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      timer: null,
      list: []
    }
  },

  watch: {
    serachKeys: {
      // handler () {
      //   clearTimeout(this.timer)
      //   this.timer = setTimeout(() => {
      //     this.getSteerData()
      //   }, 800)
      // },
      handler: debounce(function () {
        this.getSteerData()
      }, 800),
      immediate: true
    }
  },

  created () {

  },

  methods: {
    async getSteerData () {
      try {
        const { data: { data: res } } = await steerData(this.serachKeys)
        this.list = res.options
        console.log(res)
      } catch (err) {
        console.log(121)
      }
    },
    // 处理搜索关键字高亮
    lightStr (val) {
      const reg = new RegExp(this.serachKeys, 'gi')
      const newStr = val.replace(reg, '<span style="color: red">' + this.serachKeys + '</span>')
      return newStr
    }
  }
}
</script>

<style scoped lang='less'>

</style>
